import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      component: () => import('@/views/login/index.vue')
    },
    {
      path: '/',
      component: () => import('@/views/layout/index.vue'),
      children: [
        {
          path: '',
          component: () => import('@/views/home/index.vue')
        },
        {
          path: 'map',
          component: () => import('@/views/map/index.vue')
        },
        {
          path: 'province/:area',
          component: () => import('@/views/province/index.vue')
        },
        {
          path: 'city',
          component: () => import('@/views/city/index.vue')
        }
      ]
    }
  ],
  scrollBehavior(to, from, savedPosition) {
    // 始终滚动到顶部
    return { top: 0 }
  }
})

// 导航守卫
router.beforeEach(to => {
  const userStore = useUserStore()
  if (!userStore.userInfo.token && to.path !== '/login') return '/login'
})

export default router
